<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>任务管理器</title>
  <!-- 引入Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- 引入Font Awesome -->
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <!-- 引入腾讯云开发SDK -->
  <script src="https://imgcache.qq.com/qcloud/tcbjs/1.19.5/tcb.js"></script>
  
  <!-- 配置Tailwind自定义颜色和字体 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#3B82F6',
            secondary: '#10B981',
            danger: '#EF4444',
            dark: '#1F2937',
            light: '#F3F4F6'
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>
  
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .task-shadow {
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
      }
      .slide-in {
        animation: slideIn 0.3s ease forwards;
      }
      @keyframes slideIn {
        from { transform: translateY(20px); opacity: 0; }
        to { transform: translateY(0); opacity: 1; }
      }
    }
  </style>
</head>
<body class="bg-gray-50 font-sans min-h-screen">
  <!-- 顶部导航栏 -->
  <header class="bg-primary text-white shadow-md fixed top-0 left-0 right-0 z-50">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
      <h1 class="text-xl font-bold">任务管理器</h1>
      <div class="flex space-x-4">
        <button id="syncBtn" class="p-2 hover:bg-primary-600 rounded-full transition-colors">
          <i class="fa fa-refresh"></i>
        </button>
        <button id="userBtn" class="p-2 hover:bg-primary-600 rounded-full transition-colors">
          <i class="fa fa-user"></i>
        </button>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="container mx-auto px-4 pt-20 pb-24">
    <!-- 任务筛选 -->
    <div class="flex justify-between items-center my-6">
      <div class="flex space-x-2 overflow-x-auto pb-2">
        <button class="filter-btn active px-4 py-2 bg-primary text-white rounded-full text-sm whitespace-nowrap" data-filter="all">全部</button>
        <button class="filter-btn px-4 py-2 bg-gray-200 text-gray-700 rounded-full text-sm whitespace-nowrap" data-filter="pending">待办</button>
        <button class="filter-btn px-4 py-2 bg-gray-200 text-gray-700 rounded-full text-sm whitespace-nowrap" data-filter="completed">已完成</button>
      </div>
      <button id="sortBtn" class="p-2 bg-gray-200 rounded-full">
        <i class="fa fa-sort"></i>
      </button>
    </div>

    <!-- 任务列表 -->
    <div id="taskList" class="space-y-3">
      <!-- 任务项将通过JS动态生成 -->
      <div class="text-center py-10 text-gray-500">
        <i class="fa fa-tasks text-4xl mb-3 opacity-30"></i>
        <p>暂无任务，点击下方按钮添加</p>
      </div>
    </div>
  </main>

  <!-- 添加任务按钮 -->
  <button id="addTaskBtn" class="fixed bottom-8 right-8 bg-primary text-white w-14 h-14 rounded-full shadow-lg flex items-center justify-center text-2xl hover:bg-primary-600 transition-all transform hover:scale-110">
    <i class="fa fa-plus"></i>
  </button>

  <!-- 添加任务模态框 -->
  <div id="taskModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden items-center justify-center p-4">
    <div class="bg-white rounded-xl w-full max-w-md p-6 shadow-2xl slide-in">
      <h2 class="text-xl font-bold mb-4">添加新任务</h2>
      <form id="taskForm">
        <div class="mb-4">
          <label for="taskTitle" class="block text-sm font-medium text-gray-700 mb-1">任务名称</label>
          <input type="text" id="taskTitle" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="输入任务名称" required>
        </div>
        <div class="mb-4">
          <label for="taskDesc" class="block text-sm font-medium text-gray-700 mb-1">任务描述</label>
          <textarea id="taskDesc" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="输入任务描述（可选）"></textarea>
        </div>
        <div class="mb-6">
          <label for="taskDate" class="block text-sm font-medium text-gray-700 mb-1">截止日期</label>
          <input type="date" id="taskDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
        </div>
        <div class="flex justify-end space-x-3">
          <button type="button" id="cancelBtn" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">取消</button>
          <button type="submit" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-600">添加</button>
        </div>
      </form>
    </div>
  </div>

  <script>
    // 初始化云开发环境
    let app;
    let db;
    let tasks = [];
    let currentFilter = 'all';

    // DOM元素
    const taskList = document.getElementById('taskList');
    const addTaskBtn = document.getElementById('addTaskBtn');
    const taskModal = document.getElementById('taskModal');
    const taskForm = document.getElementById('taskForm');
    const cancelBtn = document.getElementById('cancelBtn');
    const syncBtn = document.getElementById('syncBtn');
    const filterBtns = document.querySelectorAll('.filter-btn');

    // 初始化云开发
    async function initCloud() {
      try {
        // 初始化云开发应用 - 请替换为你的环境ID
        app = tcb.init({
          env: "cloud1-4gyf2xxu3cf9ece6"  // 这里需要替换为你自己的环境ID
        });
        
        // 获取数据库引用
        db = app.database();
        
        // 登录（匿名登录）
        await app.auth().anonymousAuthProvider().signIn();
        console.log('云开发初始化成功');
        
        // 加载任务
        loadTasks();
        
      } catch (error) {
        console.error('云开发初始化失败:', error);
        showToast('云服务连接失败，请检查配置');
      }
    }

    // 加载任务
    async function loadTasks() {
      try {
        // 显示加载状态
        taskList.innerHTML = '<div class="text-center py-10"><i class="fa fa-spinner fa-spin text-primary text-2xl"></i></div>';
        
        // 从云数据库获取任务
        const res = await db.collection('tasks')
          .orderBy('createdAt', 'desc')
          .get();
          
        tasks = res.data || [];
        renderTasks();
        showToast(`加载了 ${tasks.length} 个任务`);
        
      } catch (error) {
        console.error('加载任务失败:', error);
        showToast('加载任务失败');
        taskList.innerHTML = '<div class="text-center py-10 text-gray-500"><i class="fa fa-exclamation-triangle text-xl mb-3"></i><p>加载失败，请重试</p></div>';
      }
    }

    // 渲染任务列表
    function renderTasks() {
      // 根据当前筛选条件过滤任务
      let filteredTasks = tasks;
      if (currentFilter === 'pending') {
        filteredTasks = tasks.filter(task => !task.completed);
      } else if (currentFilter === 'completed') {
        filteredTasks = tasks.filter(task => task.completed);
      }
      
      if (filteredTasks.length === 0) {
        taskList.innerHTML = '<div class="text-center py-10 text-gray-500"><i class="fa fa-tasks text-4xl mb-3 opacity-30"></i><p>暂无任务，点击下方按钮添加</p></div>';
        return;
      }
      
      taskList.innerHTML = '';
      filteredTasks.forEach(task => {
        const taskItem = document.createElement('div');
        taskItem.className = 'bg-white rounded-xl p-4 task-shadow slide-in';
        taskItem.setAttribute('data-id', task._id);
        
        // 格式化日期
        const formattedDate = task.dueDate ? new Date(task.dueDate).toLocaleDateString() : '';
        
        taskItem.innerHTML = `
          <div class="flex items-start">
            <button class="task-check mr-3 mt-1 flex-shrink-0" data-id="${task._id}">
              <i class="fa ${task.completed ? 'fa-check-circle text-secondary text-xl' : 'fa-circle-o text-gray-300 text-xl hover:text-primary'}"></i>
            </button>
            <div class="flex-grow">
              <h3 class="font-medium ${task.completed ? 'text-gray-400 line-through' : 'text-dark'}">${task.title}</h3>
              ${task.description ? `<p class="text-sm text-gray-500 mt-1 ${task.completed ? 'line-through' : ''}">${task.description}</p>` : ''}
              ${formattedDate ? `<div class="text-xs text-gray-400 mt-2 flex items-center">
                <i class="fa fa-calendar-o mr-1"></i> 截止: ${formattedDate}
              </div>` : ''}
            </div>
            <button class="task-delete text-gray-400 hover:text-danger p-2" data-id="${task._id}">
              <i class="fa fa-trash-o"></i>
            </button>
          </div>
        `;
        
        taskList.appendChild(taskItem);
      });
      
      // 添加事件监听
      document.querySelectorAll('.task-check').forEach(btn => {
        btn.addEventListener('click', toggleTaskStatus);
      });
      
      document.querySelectorAll('.task-delete').forEach(btn => {
        btn.addEventListener('click', deleteTask);
      });
    }

    // 添加任务
    async function addTask(e) {
      e.preventDefault();
      
      const title = document.getElementById('taskTitle').value.trim();
      const description = document.getElementById('taskDesc').value.trim();
      const dueDate = document.getElementById('taskDate').value;
      
      if (!title) return;
      
      try {
        // 添加到云数据库
        const res = await db.collection('tasks').add({
          title,
          description,
          dueDate: dueDate ? new Date(dueDate).toISOString() : null,
          completed: false,
          createdAt: new Date().toISOString()
        });
        
        // 更新本地任务列表
        tasks.unshift({
          _id: res._id,
          title,
          description,
          dueDate: dueDate ? new Date(dueDate).toISOString() : null,
          completed: false,
          createdAt: new Date().toISOString()
        });
        
        renderTasks();
        taskForm.reset();
        taskModal.classList.remove('flex');
        taskModal.classList.add('hidden');
        
        showToast('任务添加成功');
        
      } catch (error) {
        console.error('添加任务失败:', error);
        showToast('添加任务失败');
      }
    }

    // 切换任务状态
    async function toggleTaskStatus(e) {
      const taskId = e.currentTarget.getAttribute('data-id');
      const task = tasks.find(t => t._id === taskId);
      
      if (!task) return;
      
      try {
        // 更新云数据库
        await db.collection('tasks').doc(taskId).update({
          completed: !task.completed
        });
        
        // 更新本地任务列表
        task.completed = !task.completed;
        renderTasks();
        
        showToast(task.completed ? '任务已完成' : '任务已恢复');
        
      } catch (error) {
        console.error('更新任务状态失败:', error);
        showToast('更新失败');
      }
    }

    // 删除任务
    async function deleteTask(e) {
      e.stopPropagation();
      const taskId = e.currentTarget.getAttribute('data-id');
      
      if (!confirm('确定要删除这个任务吗？')) return;
      
      try {
        // 从云数据库删除
        await db.collection('tasks').doc(taskId).remove();
        
        // 从本地任务列表删除
        tasks = tasks.filter(task => task._id !== taskId);
        renderTasks();
        
        showToast('任务已删除');
        
      } catch (error) {
        console.error('删除任务失败:', error);
        showToast('删除失败');
      }
    }

    // 显示提示消息
    function showToast(message) {
      // 检查是否已有toast
      let toast = document.querySelector('.toast');
      if (toast) {
        toast.remove();
      }
      
      toast = document.createElement('div');
      toast.className = 'toast fixed bottom-20 left-1/2 transform -translate-x-1/2 bg-dark text-white px-4 py-2 rounded-lg shadow-lg z-50';
      toast.textContent = message;
      document.body.appendChild(toast);
      
      // 3秒后自动消失
      setTimeout(() => {
        toast.classList.add('opacity-0', 'transition-opacity', 'duration-300');
        setTimeout(() => toast.remove(), 300);
      }, 3000);
    }

    // 事件监听
    addTaskBtn.addEventListener('click', () => {
      taskModal.classList.remove('hidden');
      taskModal.classList.add('flex');
      document.getElementById('taskTitle').focus();
    });

    cancelBtn.addEventListener('click', () => {
      taskForm.reset();
      taskModal.classList.remove('flex');
      taskModal.classList.add('hidden');
    });

    taskForm.addEventListener('submit', addTask);

    syncBtn.addEventListener('click', () => {
      loadTasks();
      showToast('正在同步...');
    });

    // 筛选按钮事件
    filterBtns.forEach(btn => {
      btn.addEventListener('click', () => {
        // 更新按钮样式
        filterBtns.forEach(b => {
          b.classList.remove('active', 'bg-primary', 'text-white');
          b.classList.add('bg-gray-200', 'text-gray-700');
        });
        btn.classList.remove('bg-gray-200', 'text-gray-700');
        btn.classList.add('active', 'bg-primary', 'text-white');
        
        // 更新筛选条件
        currentFilter = btn.getAttribute('data-filter');
        renderTasks();
      });
    });

    // 点击模态框外部关闭
    taskModal.addEventListener('click', (e) => {
      if (e.target === taskModal) {
        taskForm.reset();
        taskModal.classList.remove('flex');
        taskModal.classList.add('hidden');
      }
    });

    // 初始化应用
    window.addEventListener('DOMContentLoaded', initCloud);
  </script>
</body>
</html>
